package com.zt.proxy.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.zt.proxy.exception.ServiceException;

public class ParamUtil {

    public static Object[] parseJson(String jsonStr, Method invokeMethod) {

        jsonStr = jsonStr.trim();

        // we should convert to array model if more the one parameter prevent someone forgetting about it.
        String json;
        if (invokeMethod.getParameters().length > 0) {
            if (StringUtils.isEmpty(jsonStr)) {
                throw new ServiceException("json parameter can't be blank.");
            }
            if (jsonStr.startsWith("[") && jsonStr.endsWith("]")) {
                json = jsonStr;
            } else {
                json = "[" + jsonStr + "]";
            }
        } else {
            json = jsonStr;
        }

        List<Object> list = JSON.parseArray(json, Object.class);

        return list.toArray();
    }

    public static String[] getparamTypes(Method method) {
        List<String> types = new ArrayList<>();
        Class<?>[] parameterTypes = method.getParameterTypes();
        if(parameterTypes != null && parameterTypes.length > 0){
            for (Class<?> clz : parameterTypes) {
                types.add(clz.getName());
            }
            return types.toArray(new String[types.size()]);
        }
        return new String[]{};
    }
}
